
public class PlayerSkeleton {

	//implement this function to have a working system
	public int pickMove(State s, int[][] legalMoves) {
		
		int numberOfMoves = legalMoves.length;
		int[] heuristic = new int[numberOfMoves];
		
		for (int i=0; i<numberOfMoves; i++)
			heuristic[i] = testMove(s, legalMoves[i][State.ORIENT], legalMoves[i][State.SLOT]);
		
		int best = 0;
		for (int i=1; i<numberOfMoves; i++)
			if (heuristic[i] > heuristic[best])
				best = i;
		
		return best;
	}
	
	public static void main(String[] args) {
		State s = new State();
		new TFrame(s);
		PlayerSkeleton p = new PlayerSkeleton();
		while(!s.hasLost()) {
			s.makeMove(p.pickMove(s,s.legalMoves()));
			s.draw();
			s.drawNext(0,0);
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("You have completed "+s.getRowsCleared()+" rows.");
	}
	
	private int testMove(State s, int orient, int slot) {
		// copy data to execute test move
		int[][] field = s.getField();
		int[][] testField = new int[State.ROWS][State.COLS];
		
		int[] top = s.getTop();
		int[] testTop = new int[State.COLS];
		
		int nextPiece = s.getNextPiece();
		int turn = s.getTurnNumber();

		for (int i=0; i<State.ROWS; i++)
			for (int j=0; j<State.COLS; j++)
				testField[i][j] = field[i][j];
		
		for (int i=0; i<State.COLS; i++)
			testTop[i] = top[i];
		
		// execute move
		
		//height if the first column makes contact
		int height = top[slot]-State.getpBottom()[nextPiece][orient][0];
		//for each column beyond the first in the piece
		for(int c = 1; c < State.getpWidth()[nextPiece][orient];c++) {
			height = Math.max(height,top[slot+c]-State.getpBottom()[nextPiece][orient][c]);
		}
		
		//check if game ended
		if(height+State.getpHeight()[nextPiece][orient] >= State.ROWS)
			return -2000000000;

		//for each column in the piece - fill in the appropriate blocks
		for(int i = 0; i < State.getpWidth()[nextPiece][orient]; i++) {
			
			//from bottom to top of brick
			for(int h = height+State.getpBottom()[nextPiece][orient][i]; h < height+State.getpTop()[nextPiece][orient][i]; h++) {
				testField[h][i+slot] = turn;
			}
		}
		
		//adjust top
		for(int c = 0; c < State.getpWidth()[nextPiece][orient]; c++) {
			testTop[slot+c]=height+State.getpTop()[nextPiece][orient][c];
		}
		
		// return value of heuristic function
		return 0 - countHoles(testField, testTop) - height;
	}
	
	// number of holes
	private int countHoles(int[][] board, int[] top) {
		int holes = 0;
		
		for (int i = 0; i < State.COLS; i++) {
			for (int j = 0; j < top[i]; j++) {
				if (board[j][i] == 0)
					holes++;
			}
		}
		
		return holes;
	}
}
